package com.fdq.dianping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fdq.dianping.entity.Blog;
import com.fdq.dianping.entity.BlogComments;
import com.fdq.dianping.entity.Result;
import com.fdq.dianping.entity.User;
import com.fdq.dianping.entity.dto.UserDto;
import com.fdq.dianping.mapper.BlogCommentsMapper;
import com.fdq.dianping.service.IBlogCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdq.dianping.service.UserService;
import com.fdq.dianping.util.ThreadLocalUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import static com.fdq.dianping.util.Constants.BlogComment_Like;
import static com.fdq.dianping.util.Constants.Blog_Like;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fdq
 * @since 2025-01-25
 */
@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsMapper, BlogComments> implements IBlogCommentsService {
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private UserService userService;

    @Override
    public Result saveBlogComment(BlogComments blogComments) {
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        UserDto user = BeanUtil.mapToBean(userMap,UserDto.class,true);
        blogComments.setUserId(user.getId());
        boolean save = save(blogComments);
        if(save){
            return Result.success();
        }else {
            return Result.error("添加评论失败");
        }

    }

    @Override
    public Result getBlogComments(Long id) {
        QueryWrapper<BlogComments> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("blog_id",id);
        queryWrapper.orderByDesc("liked");
        List<BlogComments> blogComments = list(queryWrapper);
        blogComments.forEach(blogComment -> {
            this.isBlogLiked(blogComment);
            this.queryBlogCommentUser(blogComment);
        });
        return Result.success(blogComments);
    }

    @Override
    public Result likeBlogComment(Long id) {
        //判断当前用户是否点赞过       使用redis的SortedSet数据类型判断,SortedSet相当于一个可以排序的集合,这里按时间排序
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        Integer userIdObject =(Integer) userMap.get("id");
        Long userId = Long.valueOf(userIdObject);

        String key = BlogComment_Like+id;        //键为前缀+点评id
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());

        if(BooleanUtil.isFalse(isMember)){
            //如果未点赞可以点赞，点赞+1
            boolean success = update().setSql("liked = liked + 1").eq("id", id).update();
            if(success){
                //在redis的集合set中添加已经点赞的用户id
                stringRedisTemplate.opsForSet().add(key,userId.toString());
            }
        }else {
            //如果已经点赞，取消点赞，点赞-1
            boolean success = update().setSql("liked = liked - 1").eq("id", id).update();
            if(success){
                //在redis的集合set中删除已经点赞的用户id
                stringRedisTemplate.opsForSet().remove(key,userId.toString());
            }
        }

        return Result.success();
    }


    //给blogComment的isLiked属性赋值，表示当前用户是否给博客评论点赞过（前端渲染用）
    private void isBlogLiked(BlogComments blogComments) {
        //获取当前登录用户信息
        Map<String,Object> userMap = ThreadLocalUtil.get();
        if(userMap == null){
            // 用户没有登录，不用查询其是否点过赞
            return;
        }
        Integer userIdObject =(Integer) userMap.get("id");
        Long userId = Long.valueOf(userIdObject);

        //键为前缀+点评id
        String key = BlogComment_Like+blogComments.getId();
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());

        blogComments.setIsLike(BooleanUtil.isTrue(isMember));
    }

    private void queryBlogCommentUser(BlogComments blogComments) {
        Long userId = blogComments.getUserId();
        User user = userService.getById(userId);
        blogComments.setIcon(user.getIcon());
        blogComments.setName(user.getNickName());
    }
}
